package com.smartphonedev.activity;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;

import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
import com.smartphonedev.drawroute.GoogleParser;
import com.smartphonedev.drawroute.Parser;
import com.smartphonedev.drawroute.Route;
import com.smartphonedev.drawroute.RouteOverlay;
import com.smartphonedev.files.FileUtils;
import com.smartphonedev.function.Ringtones;
import com.smartphonedev.function.SmsFunc;
import com.smartphonedev.function.Storage;
import com.smartphonedev.overlay.MyItemizedOverlay;
import com.smartphonedev.sliding.SlidingPanel;
import com.smartphonedev.variables.Constants;

public class TestTab1Activity extends MapActivity {

	// map
	private LocationManager lm;
	private LocationListener ll;
	private MapView mapView;
	private MapController mc;
	private String provider;
	private MyLocationOverlay me = null;
	private int defaultLat =(int)(20.996967); 
	private int defaultLong =(int)(105.861601);
	private GeoPoint defaultGeoPint = new GeoPoint(defaultLat,defaultLong);
	private static final long minDistance = 1; // meter
	private static final long minTime = 123; // millis

	ArrayAdapter<String> adapter;
	AutoCompleteTextView auto;
	Calendar c;
	Drawable drawable, drawable2;
	EditText et, et2, et3, et4;
	final Context context = this;
	List<Overlay> mapOverlays;
	MyItemizedOverlay itemizedoverlay, itemizedoverlay2;
	Geocoder geocoder;
	//	private MapView mapView;
	//	private MapController mc;
	private Animation animShow, animHide;
	//	protected LocationManager lm;
	SharedPreferences sp;
	StringBuffer sb, sb2;
	String latlon, getlat, getlon, mylocation, date, month, year, hour, minute, getlocationshare;
	String local[]={"BaDinh", "CauGiay", "CoNhue", "DongDa", "GiaLam", "HaiBaTrung", "HoanKiem","HoangMai",
			"LinhNam", "LongBien", "MinhKhai", "MyDinh", "NgaTuSo", "PhoHue", "ThanhXuan", "TamTrinh", "ThanhNhan", 
			"ThuyKhue", "TinhYeu", "TranKhanhDu", "VietNam", "Vinh Tuy"};     
	TextView tv;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.tab1);
		mapView = (MapView) findViewById(R.id.MV1);
		mapView.setTraffic(true);
		mc = mapView.getController();
		lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		lm.requestLocationUpdates(
				LocationManager.NETWORK_PROVIDER, 
				minTime, 
				minDistance,
				new MyLocationListener()
				);
		geocoder = new Geocoder(this);
		drawable = this.getResources().getDrawable(R.drawable.ic_ml);
		drawable2 = this.getResources().getDrawable(R.drawable.iconblue);
		itemizedoverlay = new MyItemizedOverlay(drawable,this);
		itemizedoverlay2 = new MyItemizedOverlay(drawable2,this);
		mapOverlays = mapView.getOverlays();
		tv = (TextView)findViewById(R.id.TV1);
		sp = getSharedPreferences(Constants.foldername, 0);
		adapter =new ArrayAdapter<String>(this,android.R.layout.simple_dropdown_item_1line,local);

		//		getLocation();
		checkNotify();


		c = Calendar.getInstance();
		int getdate = c.get(Calendar.DAY_OF_MONTH);
		int getmonth = c.get(Calendar.MONTH);
		int getyear = c.get(Calendar.YEAR);
		int gethour = c.get(Calendar.HOUR_OF_DAY);
		int getminute = c.get(Calendar.MINUTE);
		date = Integer.toString(getdate);
		month = Integer.toString(getmonth);
		year = Integer.toString(getyear);
		hour = Integer.toString(gethour);
		minute = Integer.toString(getminute);

		// location manager

		setMapLocation();

	}

	// Get Location
	//	public void getLocation() {
	//
	//		Location location = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
	//		if (location != null) {
	//			latlon = String.format(
	//					// Latitude: %2$s \n Longitude: %1$s
	//					"latlon:%2$s:%1$s",
	//					location.getLongitude(), location.getLatitude()
	//					);
	//		} else {
	//
	//			Toast.makeText(context, R.string.notify, Toast.LENGTH_LONG).show();
	//
	//		}
	//
	//		String [] m = latlon.split(":");
	//		if("latlon".equals(m[0])) {
	//			getlat = (m[1]);
	//			getlon = (m[2]);
	//			Constants.currentlatitude = Double.parseDouble(getlat);
	//			Constants.currentlongitude = Double.parseDouble(getlon);
	//			mapView.setBuiltInZoomControls(true);
	//			GeoPoint point = new GeoPoint((int)(Constants.currentlatitude *  1E6),(int)(Constants.currentlongitude * 1E6));
	//			mc.animateTo(point);
	//			mc.setZoom(getZoomLevel(789));
	//			mc.setCenter(point);
	//
	//			GeoPoint point_hienthi = new GeoPoint((int)(Constants.currentlatitude *  1E6),(int)(Constants.currentlongitude * 1E6));
	//			OverlayItem overlayitem = new OverlayItem(point_hienthi, "", "");
	//			itemizedoverlay.addOverlay(overlayitem);
	//			mapOverlays.add(itemizedoverlay);
	//		}
	//	}

	public void checkNotify() {
		// Check name
		String checkname = sp.getString(Constants.keyname, Constants.keynamenotok);
		String getusername = sp.getString(Constants.saveusername, Constants.keynamenotok);
		if (checkname.equals(Constants.keynameok)) {
			tv.setText(context.getString(R.string.hello) + " " + getusername);
		} else {
			setWelcome();
		}

		// Check share
		String ok = sp.getString(Constants.keynotify, Constants.keynotnotify);
		if (ok.equals(Constants.keyshareok)) {	
			checkSMS();
		} else {
			// Check confirm share
			String checkconfirms = sp.getString(Constants.keyconfirm, Constants.none);
			if (checkconfirms.equals(Constants.keyconfirmok)) {
				checkSMSB();
			} else {
				// Check request
				String checkrequest = sp.getString(Constants.keyrequest, Constants.none);
				if (checkrequest.equals(Constants.keyrequestok)) {	
					checkSMS2();
				} else {
					// Check request accept
					String checkrequestaccept = sp.getString(Constants.keyrequestaccept, Constants.none);
					if (checkrequestaccept.equals(Constants.keyrequestacceptok)) {	
						checkSMS3();
					} else {

						// Check tracking
						String checktracking = sp.getString(Constants.keytracking, Constants.none);
						if (checktracking.equals(Constants.keytrackingok)) {	
							checkSMS4();
						} else {
							setNotify();
						}
					}
				}
			}
		}
	}

	// Display map
	public void displayMap() {
		mapView.setBuiltInZoomControls(true);
		GeoPoint point = new GeoPoint((int)(Constants.currentlatitude *  1E6),(int)(Constants.currentlongitude * 1E6));
		mc.animateTo(point);
		mc.setCenter(point);

		GeoPoint point_hienthi = new GeoPoint((int)(Constants.currentlatitude *  1E6),(int)(Constants.currentlongitude * 1E6));
		OverlayItem overlayitem = new OverlayItem(point_hienthi, "", "");
		itemizedoverlay.addOverlay(overlayitem);
		mapOverlays.add(itemizedoverlay);

	}

	// Clear icon	
	public void clearIcon() {

		mapOverlays.clear();

	}

	private class MyLocationListener implements LocationListener {
		public void onLocationChanged(Location location) {
		}
		public void onStatusChanged(String s, int i, Bundle b) {
		}
		public void onProviderDisabled(String s) {
		}
		public void onProviderEnabled(String s) {
		}
	}

	public void setButtonMyLocation(View v) {
		// custom dialog
		final Dialog dialog = new Dialog(context);
		dialog.setContentView(R.layout.location);
		dialog.setCancelable(true);
		dialog.setTitle(context.getString(R.string.currentlocation));

		String getmylocation3 = sp.getString(Constants.currentlocation2, context.getString(R.string.loadlocation));
		final EditText edit = (EditText) dialog.findViewById(R.id.MYLOCATION);
		edit.setText(getmylocation3);
		Button dialogButton = (Button) dialog.findViewById(R.id.SAVELOCATION);
		dialogButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if (edit.getText().toString().equals("")) {
					setNotifyNotSuccess(context.getString(R.string.error11));
					dialog.dismiss();
				} else {
					FileUtils.addLineToFile("<?xml version='1.0' encoding='UTF-8'?>" + "<div style='text-align:center'><div style='background:#dddddd;padding:5px'><div style='background:white;padding:5px;border:1px solid #999999'><div style='text-align:left'><font color='#ff0000'>" + "<b>" + context.getString(R.string.you) + "</b></font><font color='#3366FF'>" + " " + context.getString(R.string.savedlocaton)  + " " + edit.getText().toString() + "</font><br/><div style='text-align:right'><i style='color:#ff6633'>" + context.getString(R.string.date) + " " + date + "/" + month + "/" + year + " " + context.getString(R.string.time) + " " + hour + ":" + minute + "</i></div>" + "</div></div></div></div>", context.getString(R.string.filename), context);
					FileUtils.addLineToFile(context.getString(R.string.you) + " " + context.getString(R.string.savedlocaton) + " " + edit.getText().toString() + " " + "(" + context.getString(R.string.date) + " " + date + "/" + month + "/" + year + " " + context.getString(R.string.time) + " " + hour + ":" + minute + ")" + ". ", context.getString(R.string.filename2), context);
					dialog.dismiss();
					setNotifySuccess(context.getString(R.string.notify25));
				}
			}
		});
		Button dialogButton2 = (Button) dialog.findViewById(R.id.BACKLOCATION);
		dialogButton2.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				dialog.dismiss();

			}
		});

		dialog.show();

	}

	public void setButtonShareLocation(View v) {
		LayoutInflater li = LayoutInflater.from(context);
		View sv = li.inflate(R.layout.share, null);

		AlertDialog.Builder adb = new AlertDialog.Builder(context);
		adb.setTitle(R.string.sharelocation);
		adb.setIcon(R.drawable.share);
		adb.setView(sv);
		et = (EditText) sv.findViewById(R.id.SMSNUMBER);
		String getlastnumber = sp.getString(Constants.numbersendshare, "");
		et.setText(getlastnumber);
		final Button local = (Button) findViewById(R.id.BUTTON1);
		Constants.currentlocation = local.getText().toString();
		adb.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {

				SmsManager sms = SmsManager.getDefault();
				String number = et.getText().toString();
				String getusernametosend = sp.getString(Constants.saveusername, Constants.keynamenotok);

				if (number.equals("")) {
					setNotifyNotSuccess(context.getString(R.string.error2));
				} else {

					try {
						sms.sendTextMessage(number, null, "format:" + Constants.currentlatitude + ":" + Constants.currentlongitude + ":" + getusernametosend, null, null);
						setNotifySuccess(context.getString(R.string.notify17) + " " + context.getString(R.string.location) + " " + Constants.currentlocation);
						FileUtils.addLineToFile("<?xml version='1.0' encoding='UTF-8'?>" + "<div style='text-align:center'><div style='background:#dddddd;padding:5px'><div style='background:white;padding:5px;border:1px solid #999999'><div style='text-align:left'><font color='#ff0000'>" + "<b>" + context.getString(R.string.you) + "</b></font><font color='#3366FF'>" + " " + context.getString(R.string.sharelocationdone)  + " " + Constants.currentlocation + " " + context.getString(R.string.tonumber) + " " + number + "</font><br/><div style='text-align:right'><i style='color:#ff6633'>" + context.getString(R.string.date) + " " + date + "/" + month + "/" + year + " " + context.getString(R.string.time) + " " + hour + ":" + minute + "</i></div>" + "</div></div></div></div>", context.getString(R.string.filename), context);
						SharedPreferences.Editor editor = sp.edit();
						editor.putString(Constants.numbersendshare, number);
						editor.commit();
					} catch (Exception e) {
						setNotifyNotSuccess(context.getString(R.string.error1));
						e.printStackTrace();
						Log.e("Error", "message not sent");
					}
				}
			}
		});
		adb.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.cancel();

			}
		});
		adb.show();
	}


	// Run when receiver a local
	public void checkSMS() {
		Uri uriSMSURI = Uri.parse("content://sms/inbox");
		Cursor cur = getContentResolver().query(uriSMSURI, null, null, null,null);
		String sms = "";
		cur.moveToNext();
		sms += cur.getString(11)+"!c!";
		String [] m = sms.split("!c!");
		String sms2 = (m[0]);	
		String [] m2 = sms2.split(":");
		if((m2[0]).equals("format")) {
			String getlat = (m2[1]);
			String getlon = (m2[2]);
			Double latnhe = Double.parseDouble(getlat);
			Double lonnhe = Double.parseDouble(getlon);
			sb = new StringBuffer();
			try {
				List<Address> addresses = geocoder.getFromLocation(latnhe, lonnhe, 10); //<10>
				for (Address address : addresses) {
					sb.append(address.getAddressLine(0) + ", ");
				}
			} catch (IOException e) {
				Log.e("Log me", "Could not get geocoder data", e);
			}
			Constants.nameshare = (m2[3]);
			Ringtones.play2(getApplicationContext(), R.raw.notifysuccess);
			final SlidingPanel popup = (SlidingPanel) findViewById(R.id.popup_window);
			// Hide the popup initially.....
			popup.setVisibility(View.GONE);

			animShow = AnimationUtils.loadAnimation( this, R.anim.notify_show);
			animHide = AnimationUtils.loadAnimation( this, R.anim.notify_hide);
			popup.setVisibility(View.VISIBLE);
			popup.startAnimation( animShow );
			final ImageButton   showButton = (ImageButton) findViewById(R.id.show_popup_button);
			final ImageButton   hideButton = (ImageButton) findViewById(R.id.hide_popup_button);
			showButton.setEnabled(false);
			showButton.setBackgroundResource(R.drawable.right);
			hideButton.setEnabled(true);
			hideButton.setOnClickListener(new View.OnClickListener() {
				public void onClick(View view) {
					popup.startAnimation( animShow );
				}});
			Uri uriSMSURIaa = Uri.parse("content://sms/inbox");
			Cursor curaa = getContentResolver().query(uriSMSURIaa, null, null, null,null);
			String smsaa = "";
			curaa.moveToNext();
			smsaa += cur.getString(2)+"!n!";
			String [] maa = smsaa.split("!n!");
			String number = (maa[0]);	
			String text = String.format(context.getString(R.string.notify18) + " " + Constants.nameshare + ", " + context.getString(R.string.notify18b) + " " + number + "\n" + context.getString(R.string.latitude) + ": " + getlat + "\n" + context.getString(R.string.longitude) + ": " + getlon + "\n" + context.getString(R.string.notify18c));
			final TextView showmore = (TextView) findViewById(R.id.NOTIFYINFO);
			showmore.setText(text);
			showmore.setTextColor(Color.CYAN);

			final Button show = (Button) findViewById(R.id.MULTITASK);
			show.setText(R.string.displaytomap);
			show.setClickable(true);
			show.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {

					Uri uriSMSURI = Uri.parse("content://sms/inbox");
					Cursor cur = getContentResolver().query(uriSMSURI, null, null, null,null);
					String sms = "";
					cur.moveToNext();
					sms += cur.getString(11)+"!c!";         
					String [] m = sms.split("!c!");
					String sms2 = (m[0]);	
					SharedPreferences settings = context.getSharedPreferences(Constants.foldername, 0);
					SharedPreferences.Editor editor = settings.edit();
					editor.putString(Constants.lastreceiverlocation, sms2);
					editor.commit();
					Storage.setLastShare(context);
					String [] m2 = sms2.split(":");
					if((m2[0]).equals("format")) {
						clearIcon();
						displayMap();
						String getlat2 = (m2[1]);
						String getlon2 = (m2[2]);

						double lat = Double.parseDouble(getlat2);
						double lon = Double.parseDouble(getlon2);
						Constants.jsonURL = "http://maps.googleapis.com/maps/api/directions/json?origin=" + Constants.currentlatitude + "," + Constants.currentlongitude + "&destination=" + lat + "," + lon + "&sensor=false";

						GeoPoint srcGeoPoint = new GeoPoint((int) (Constants.currentlatitude * 1E6),
								(int) (Constants.currentlongitude * 1E6));
						GeoPoint destGeoPoint = new GeoPoint((int) (lat * 1E6),
								(int) (lon * 1E6));
						Double result = CalculationByDistance(srcGeoPoint, destGeoPoint) *1000;
						Double result2 = CalculationByDistance(srcGeoPoint, destGeoPoint);
						int i = (int) result.doubleValue();
						int i2 = (int) result2.doubleValue();
						String meter = Integer.toString(i);
						String kilometer = Integer.toString(i2);
						mapView.setBuiltInZoomControls(true);
						GeoPoint point = new GeoPoint((int)(lat *  1E6),(int)(lon * 1E6));
						mc.animateTo(point);
						mc.setZoom(getZoomLevel(result));
						//						mc.setZoom(18);//1-21

						GeoPoint point_hienthi = new GeoPoint((int)(lat *  1E6),(int)(lon * 1E6));
						OverlayItem overlayitem = new OverlayItem(point_hienthi, "", "");
						itemizedoverlay2.addOverlay(overlayitem);
						List<Overlay> mapOverlays = mapView.getOverlays();
						mapOverlays.add(itemizedoverlay2);
						Storage.clearNotify(context);

						Route route = directions(new GeoPoint((int)(Constants.currentlatitude),(int)(Constants.currentlongitude)), new GeoPoint((int)(26.3*1E6),(int)(50.7*1E6)));
						RouteOverlay routeOverlay = new RouteOverlay(route, Color.BLUE);
						mapView.getOverlays().add(routeOverlay);
						mapView.invalidate();
						setNotify();

						try {
							List<Address> addresses = geocoder.getFromLocation(lat, lon, 10); //<10>
							for (Address address : addresses) {
								final TextView locationDescription2 = new TextView(context);
								locationDescription2.setText("");
								locationDescription2.append(address.getAddressLine(0));
							}
						} catch (IOException e) {
							Log.e("Log me", "Could not get geocoder data", e);
						}
						Double test = result/500;
						int lastresult = (int) test.doubleValue();
						String minuteresult = Integer.toString(lastresult);
						FileUtils.addLineToFile("<?xml version='1.0' encoding='UTF-8'?>" + "<div style='text-align:center'><div style='background:#dddddd;padding:5px'><div style='background:white;padding:5px;border:1px solid #999999'><div style='text-align:left'><font color='#ff0000'>" + "<b>" + Constants.nameshare + "</b></font><font color='#3366FF'>" + " " + context.getString(R.string.sharelocationdone)  + " " + sb.toString() + "</font><br/><div style='text-align:right'><i style='color:#ff6633'>" + context.getString(R.string.date) + " " + date + "/" + month + "/" + year + " " + context.getString(R.string.time) + " " + hour + ":" + minute + "</i></div>" + "</div></div></div></div>", context.getString(R.string.filename), context);
						Uri uriSMSURIaa = Uri.parse("content://sms/inbox");
						Cursor curaa = getContentResolver().query(uriSMSURIaa, null, null, null,null);
						String smsaa = "";
						curaa.moveToNext();
						smsaa += cur.getString(2)+"!n!";
						String [] maa = smsaa.split("!n!");
						String number = (maa[0]);	
						String getusernametosend = sp.getString(Constants.saveusername, Constants.keynamenotok);
						SmsFunc.sendASms(context, number, "confirmformat:" + getusernametosend);

						final Dialog dialog = new Dialog(context);
						dialog.setContentView(R.layout.linfo);
						dialog.setCancelable(false);
						dialog.setTitle(context.getString(R.string.location3));
						final EditText et = (EditText) dialog.findViewById(R.id.LOCATIONINFO2);
						et.setText(context.getString(R.string.notify22b2) + " " + kilometer + context.getString(R.string.kilometer) + " " + "(" + meter + " " + context.getString(R.string.meter) + ")" + " " + context.getString(R.string.notify22b) + ". " + context.getString(R.string.location2) + ": " + sb.toString() + ". " + context.getString(R.string.notify23) + " " + minuteresult + " " + context.getString(R.string.notify23b));
						Button dialogButton = (Button) dialog.findViewById(R.id.CONFIRMINFO);
						dialogButton.setOnClickListener(new OnClickListener() {
							@Override
							public void onClick(View v) {
								dialog.dismiss();
								Toast.makeText(context, context.getString(R.string.notify24), Toast.LENGTH_LONG).show();
							}
						});
						dialog.show();

					} else {
						// Nothing to do
					}
				}
			});

		} else {

			// Nothing to do

		}
	}

	// Confirm receiver a local
	public void checkSMSB() {
		Uri uriSMSURI = Uri.parse("content://sms/inbox");
		Cursor cur = getContentResolver().query(uriSMSURI, null, null, null,null);
		String sms = "";
		cur.moveToNext();
		sms += cur.getString(11)+"!c!";
		String [] m = sms.split("!c!");
		String sms2 = (m[0]);	
		String [] m2 = sms2.split(":");
		if((m2[0]).equals("confirmformat")) {
			String getname = (m2[1]);
			Ringtones.play2(getApplicationContext(), R.raw.notifysuccess);
			final SlidingPanel popup = (SlidingPanel) findViewById(R.id.popup_window);
			// Hide the popup initially.....
			popup.setVisibility(View.GONE);

			animShow = AnimationUtils.loadAnimation( this, R.anim.notify_show);
			animHide = AnimationUtils.loadAnimation( this, R.anim.notify_hide);
			popup.setVisibility(View.VISIBLE);
			popup.startAnimation( animShow );
			final ImageButton   showButton = (ImageButton) findViewById(R.id.show_popup_button);
			final ImageButton   hideButton = (ImageButton) findViewById(R.id.hide_popup_button);
			showButton.setEnabled(false);
			showButton.setBackgroundResource(R.drawable.right);
			hideButton.setEnabled(true);
			hideButton.setOnClickListener(new View.OnClickListener() {
				public void onClick(View view) {
					Storage.clearConfirmShare(context);
					setNotify();
				}});
			String text = String.format(getname + " " + context.getString(R.string.confirmformat));
			final TextView showmore = (TextView) findViewById(R.id.NOTIFYINFO);
			showmore.setText(text);
			showmore.setTextColor(Color.CYAN);

			final Button show = (Button) findViewById(R.id.MULTITASK);
			show.setText(android.R.string.ok);
			show.setClickable(true);
			show.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					Storage.clearConfirmShare(context);
					setNotify();

				}
			});
		} else {
			// Nothing to do
		}
	}


	public void setButtonGetLocation(View v) {

		LayoutInflater li = LayoutInflater.from(context);
		View sv = li.inflate(R.layout.get, null);

		AlertDialog.Builder adb = new AlertDialog.Builder(context);
		adb.setTitle(R.string.getlocation);
		adb.setIcon(R.drawable.iconblue);
		adb.setView(sv);
		et2 = (EditText) sv.findViewById(R.id.SMSNUMBERGET);
		String lastnumber2 = sp.getString(Constants.numbersendrequest, "");
		et2.setText(lastnumber2);
		adb.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				SmsManager sms2 = SmsManager.getDefault();
				String numberget = et2.getText().toString();
				String getusernametosend2 = sp.getString(Constants.saveusername, Constants.keynamenotok);

				if (numberget.equals("")) {
					setNotifyNotSuccess(context.getString(R.string.error4));
				} else {

					try {
						sms2.sendTextMessage(numberget, null, "getformat:" + getusernametosend2, null, null);
						setNotifySuccess(context.getString(R.string.notify8));
						SharedPreferences.Editor editor = sp.edit();
						editor.putString(Constants.numbersendrequest, numberget);
						editor.commit();

					} catch (Exception e) {
						setNotifyNotSuccess(context.getString(R.string.error5));
						e.printStackTrace();
						Log.e("Error", "message not sent");
					}
				}
			}
		});
		adb.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.cancel();
			}
		});
		adb.show();
	}

	// Run when receiver a request
	public void checkSMS2() {
		Uri uriSMSURI = Uri.parse("content://sms/inbox");
		Cursor cur = getContentResolver().query(uriSMSURI, null, null, null,null);
		String sms = "";
		cur.moveToNext();
		sms += cur.getString(11)+"!c!";
		String [] m = sms.split("!c!");
		String sms2 = (m[0]);	
		String [] m2 = sms2.split(":");
		if((m2[0]).equals("getformat")) {
			String getname = (m2[1]);
			Ringtones.play2(getApplicationContext(), R.raw.notifysuccess);
			final SlidingPanel popup = (SlidingPanel) findViewById(R.id.popup_window);
			// Hide the popup initially.....
			popup.setVisibility(View.GONE);

			animShow = AnimationUtils.loadAnimation( this, R.anim.notify_show);
			animHide = AnimationUtils.loadAnimation( this, R.anim.notify_hide);
			popup.setVisibility(View.VISIBLE);
			popup.startAnimation( animShow );
			final ImageButton   showButton = (ImageButton) findViewById(R.id.show_popup_button);
			final ImageButton   hideButton = (ImageButton) findViewById(R.id.hide_popup_button);
			showButton.setEnabled(false);
			showButton.setBackgroundResource(R.drawable.right);
			hideButton.setEnabled(true);
			hideButton.setOnClickListener(new View.OnClickListener() {
				public void onClick(View view) {
					notAcceptRequest();
				}});
			Uri uriSMSURIaa = Uri.parse("content://sms/inbox");
			Cursor curaa = getContentResolver().query(uriSMSURIaa, null, null, null,null);
			String smsaa = "";
			curaa.moveToNext();
			smsaa += curaa.getString(2)+"!n!";
			String [] maa = smsaa.split("!n!");
			String number = (maa[0]);
			String text = String.format(context.getString(R.string.notify19) + " " + getname + ", " + context.getString(R.string.notify19b) + " " + number);
			final TextView showmore = (TextView) findViewById(R.id.NOTIFYINFO);
			showmore.setText(text);
			showmore.setTextColor(Color.CYAN);

			final Button show = (Button) findViewById(R.id.MULTITASK);
			show.setText(R.string.notify9);
			show.setClickable(true);
			show.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {

					Uri uriSMSURIaa = Uri.parse("content://sms/inbox");
					Cursor curaa = getContentResolver().query(uriSMSURIaa, null, null, null,null);
					String smsaa = "";
					curaa.moveToNext();
					smsaa += curaa.getString(2)+"!n!";
					String [] maa = smsaa.split("!n!");
					String number2 = (maa[0]);
					String getusernametosend2 = sp.getString(Constants.saveusername, Constants.keynamenotok);

					SmsFunc.sendASms(context, number2, "receiverformat:" + Constants.currentlatitude + ":" + Constants.currentlongitude + ":" + getusernametosend2);
					Storage.deleteRequest(context);
					setNotifySuccess(context.getString(R.string.notify10));
				}
			});
		} else {
			// Nothing to do
		}
	}

	// Confirm not accept request
	public void notAcceptRequest() {
		AlertDialog.Builder adb = new AlertDialog.Builder(this);
		adb.setTitle(R.string.confirm);
		adb.setIcon(R.drawable.share);
		adb.setMessage(R.string.notify11);
		adb.setCancelable(false);
		adb.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {

				Storage.deleteRequest(context);
				setNotifySuccess(context.getString(R.string.notify12));
			}
		});
		adb.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.cancel();
			}
		});
		adb.show();

	}

	// Run when receiver a local from request
	public void checkSMS3() {
		Uri uriSMSURI = Uri.parse("content://sms/inbox");
		Cursor cur = getContentResolver().query(uriSMSURI, null, null, null,null);
		String sms = "";
		cur.moveToNext();
		sms += cur.getString(11)+"!c!";
		String [] m = sms.split("!c!");
		String sms2 = (m[0]);	
		String [] m2 = sms2.split(":");
		if((m2[0]).equals("receiverformat")) {
			String getlat = (m2[1]);
			String getlon = (m2[2]);
			Double latnhe = Double.parseDouble(getlat);
			Double lonnhe = Double.parseDouble(getlon);
			sb2 = new StringBuffer();
			try {
				List<Address> addresses = geocoder.getFromLocation(latnhe, lonnhe, 10); //<10>
				for (Address address : addresses) {
					sb2.append(address.getAddressLine(0) + ", ");
				}
			} catch (IOException e) {
				Log.e("Log me", "Could not get geocoder data", e);
			}
			Constants.nameshare = (m2[3]);
			Ringtones.play2(getApplicationContext(), R.raw.notifysuccess);
			final SlidingPanel popup = (SlidingPanel) findViewById(R.id.popup_window);
			// Hide the popup initially.....
			popup.setVisibility(View.GONE);

			animShow = AnimationUtils.loadAnimation( this, R.anim.notify_show);
			animHide = AnimationUtils.loadAnimation( this, R.anim.notify_hide);
			popup.setVisibility(View.VISIBLE);
			popup.startAnimation( animShow );
			final ImageButton   showButton = (ImageButton) findViewById(R.id.show_popup_button);
			final ImageButton   hideButton = (ImageButton) findViewById(R.id.hide_popup_button);
			showButton.setEnabled(false);
			showButton.setBackgroundResource(R.drawable.right);
			hideButton.setEnabled(true);
			hideButton.setOnClickListener(new View.OnClickListener() {
				public void onClick(View view) {
					popup.startAnimation( animShow );
				}});
			Uri uriSMSURIaa = Uri.parse("content://sms/inbox");
			Cursor curaa = getContentResolver().query(uriSMSURIaa, null, null, null,null);
			String smsaa = "";
			curaa.moveToNext();
			smsaa += cur.getString(2)+"!n!";
			String [] maa = smsaa.split("!n!");
			String number = (maa[0]);	
			String text = String.format(context.getString(R.string.notify20) + " " + Constants.nameshare + ", " + context.getString(R.string.notify18b) + " "+ number + "\n" + context.getString(R.string.latitude) + ": " + getlat + "\n" + context.getString(R.string.longitude) + ": " + getlon + "\n" + context.getString(R.string.notify18c));
			final TextView showmore = (TextView) findViewById(R.id.NOTIFYINFO);
			showmore.setText(text);
			showmore.setTextColor(Color.CYAN);

			final Button show = (Button) findViewById(R.id.MULTITASK);
			show.setText(R.string.displaytomap);
			show.setClickable(true);
			show.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					Uri uriSMSURI = Uri.parse("content://sms/inbox");
					Cursor cur = getContentResolver().query(uriSMSURI, null, null, null,null);
					String sms = "";
					cur.moveToNext();
					sms += cur.getString(11)+"!c!";         
					String [] m = sms.split("!c!");
					String sms2 = (m[0]);	
					SharedPreferences settings = context.getSharedPreferences(Constants.foldername, 0);
					SharedPreferences.Editor editor = settings.edit();
					editor.putString(Constants.lastreceiverlocation, sms2);
					editor.commit();
					Storage.setLastShare(context);
					String [] m2 = sms2.split(":");
					if((m2[0]).equals("receiverformat")) {
						clearIcon();
						displayMap();
						String getlat2 = (m2[1]);
						String getlon2 = (m2[2]);

						double lat = Double.parseDouble(getlat2);
						double lon = Double.parseDouble(getlon2);
						Constants.jsonURL = "http://maps.googleapis.com/maps/api/directions/json?origin=" + Constants.currentlatitude + "," + Constants.currentlongitude + "&destination=" + lat + "," + lon + "&sensor=false";

						GeoPoint srcGeoPoint = new GeoPoint((int) (Constants.currentlatitude * 1E6),
								(int) (Constants.currentlongitude * 1E6));
						GeoPoint destGeoPoint = new GeoPoint((int) (lat * 1E6),
								(int) (lon * 1E6));
						Double result = CalculationByDistance(srcGeoPoint, destGeoPoint) *1000;
						Double result2 = CalculationByDistance(srcGeoPoint, destGeoPoint);
						int i = (int) result.doubleValue();
						int i2 = (int) result2.doubleValue();
						String meter = Integer.toString(i);
						String kilometer = Integer.toString(i2);

						mapView.setBuiltInZoomControls(true);
						GeoPoint point = new GeoPoint((int)(lat *  1E6),(int)(lon * 1E6));
						mc.animateTo(point);
						mc.setZoom(getZoomLevel(result));
						//						mc.setZoom(18);//1-21

						GeoPoint point_hienthi = new GeoPoint((int)(lat *  1E6),(int)(lon * 1E6));
						OverlayItem overlayitem = new OverlayItem(point_hienthi, "", "");
						itemizedoverlay2.addOverlay(overlayitem);
						List<Overlay> mapOverlays = mapView.getOverlays();
						mapOverlays.add(itemizedoverlay2);
						Storage.deleteRequestAccept(context);

						Route route = directions(new GeoPoint((int)(Constants.currentlatitude),(int)(Constants.currentlongitude)), new GeoPoint((int)(26.3*1E6),(int)(50.7*1E6)));
						RouteOverlay routeOverlay = new RouteOverlay(route, Color.BLUE);
						mapView.getOverlays().add(routeOverlay);
						mapView.invalidate();
						setNotify();

						Double test = result/500;
						int lastresult = (int) test.doubleValue();
						String minuteresult = Integer.toString(lastresult);

						FileUtils.addLineToFile("<?xml version='1.0' encoding='UTF-8'?>" + "<div style='text-align:center'><div style='background:#dddddd;padding:5px'><div style='background:white;padding:5px;border:1px solid #999999'><div style='text-align:left'><font color='#ff0000'>" + "<b>" + Constants.nameshare + "</b></font><font color='#3366FF'>" + " " + context.getString(R.string.sendlocationdone)  + " " + sb2.toString() + "</font><br/><div style='text-align:right'><i style='color:#ff6633'>" + context.getString(R.string.date) + " " + date + "/" + month + "/" + year + " " + context.getString(R.string.time) + " " + hour + ":" + minute + "</i></div>" + "</div></div></div></div>", context.getString(R.string.filename), context);

						final Dialog dialog = new Dialog(context);
						dialog.setContentView(R.layout.linfo);
						dialog.setCancelable(false);
						dialog.setTitle(context.getString(R.string.location3));
						final EditText et = (EditText) dialog.findViewById(R.id.LOCATIONINFO2);
						et.setText(context.getString(R.string.notify22b3) + " " + kilometer + context.getString(R.string.kilometer) + " " + "(" + meter + " " + context.getString(R.string.meter) + ")" + " " + context.getString(R.string.notify22b) + ". " + context.getString(R.string.location2) + ": " + sb2.toString() + ". " + context.getString(R.string.notify23) + " " + minuteresult + " " + context.getString(R.string.notify23b));
						Button dialogButton = (Button) dialog.findViewById(R.id.CONFIRMINFO);
						dialogButton.setOnClickListener(new OnClickListener() {
							@Override
							public void onClick(View v) {
								dialog.dismiss();
								Toast.makeText(context, context.getString(R.string.notify24), Toast.LENGTH_LONG).show();
							}
						});
						dialog.show();
					} else {
						// Nothing to do
					}
				}
			});
		} else {

			// Nothing to do

		}
	}

	// Run when receiver tracking request
	public void checkSMS4() {
		Uri uriSMSURI = Uri.parse("content://sms/inbox");
		Cursor cur = getContentResolver().query(uriSMSURI, null, null, null,null);
		String sms = "";
		cur.moveToNext();
		sms += cur.getString(11)+"!c!";
		String [] m = sms.split("!c!");
		String sms2 = (m[0]);	
		String [] m2 = sms2.split(":");
		if((m2[0]).equals("sendcode")) {
			String getlat = (m2[1]);
			String getlon = (m2[2]);
			Double latnhe = Double.parseDouble(getlat);
			Double lonnhe = Double.parseDouble(getlon);
			sb2 = new StringBuffer();
			try {
				List<Address> addresses = geocoder.getFromLocation(latnhe, lonnhe, 10); //<10>
				for (Address address : addresses) {
					sb2.append(address.getAddressLine(0) + ", ");
				}
			} catch (IOException e) {
				Log.e("Log me", "Could not get geocoder data", e);
			}
			Constants.nameshare = (m2[3]);
			Ringtones.play2(getApplicationContext(), R.raw.notifysuccess);
			final SlidingPanel popup = (SlidingPanel) findViewById(R.id.popup_window);
			// Hide the popup initially.....
			popup.setVisibility(View.GONE);

			animShow = AnimationUtils.loadAnimation( this, R.anim.notify_show);
			animHide = AnimationUtils.loadAnimation( this, R.anim.notify_hide);
			popup.setVisibility(View.VISIBLE);
			popup.startAnimation( animShow );
			final ImageButton   showButton = (ImageButton) findViewById(R.id.show_popup_button);
			final ImageButton   hideButton = (ImageButton) findViewById(R.id.hide_popup_button);
			showButton.setEnabled(false);
			showButton.setBackgroundResource(R.drawable.right);
			hideButton.setEnabled(true);
			hideButton.setOnClickListener(new View.OnClickListener() {
				public void onClick(View view) {
					popup.startAnimation( animShow );
				}});
			Uri uriSMSURIaa = Uri.parse("content://sms/inbox");
			Cursor curaa = getContentResolver().query(uriSMSURIaa, null, null, null,null);
			String smsaa = "";
			curaa.moveToNext();
			smsaa += cur.getString(2)+"!n!";
			String [] maa = smsaa.split("!n!");
			String number = (maa[0]);	
			String text = String.format(context.getString(R.string.notify20b) + " " + Constants.nameshare + ", " + context.getString(R.string.notify18b) + " "+ number + "\n" + context.getString(R.string.latitude) + ": " + getlat + "\n" + context.getString(R.string.longitude) + ": " + getlon + "\n" + context.getString(R.string.notify18c));
			final TextView showmore = (TextView) findViewById(R.id.NOTIFYINFO);
			showmore.setText(text);
			showmore.setTextColor(Color.CYAN);

			final Button show = (Button) findViewById(R.id.MULTITASK);
			show.setText(R.string.displaytomap);
			show.setClickable(true);
			show.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {
					Uri uriSMSURI = Uri.parse("content://sms/inbox");
					Cursor cur = getContentResolver().query(uriSMSURI, null, null, null,null);
					String sms = "";
					cur.moveToNext();
					sms += cur.getString(11)+"!c!";         
					String [] m = sms.split("!c!");
					String sms2 = (m[0]);	
					SharedPreferences settings = context.getSharedPreferences(Constants.foldername, 0);
					SharedPreferences.Editor editor = settings.edit();
					editor.putString(Constants.lastreceiverlocation, sms2);
					editor.commit();
					Storage.setLastShare(context);
					String [] m2 = sms2.split(":");
					if((m2[0]).equals("sendcode")) {
						clearIcon();
						displayMap();
						String getlat2 = (m2[1]);
						String getlon2 = (m2[2]);

						double lat = Double.parseDouble(getlat2);
						double lon = Double.parseDouble(getlon2);
						Constants.jsonURL = "http://maps.googleapis.com/maps/api/directions/json?origin=" + Constants.currentlatitude + "," + Constants.currentlongitude + "&destination=" + lat + "," + lon + "&sensor=false";

						GeoPoint srcGeoPoint = new GeoPoint((int) (Constants.currentlatitude * 1E6),
								(int) (Constants.currentlongitude * 1E6));
						GeoPoint destGeoPoint = new GeoPoint((int) (lat * 1E6),
								(int) (lon * 1E6));
						Double result = CalculationByDistance(srcGeoPoint, destGeoPoint) *1000;
						Double result2 = CalculationByDistance(srcGeoPoint, destGeoPoint);
						int i = (int) result.doubleValue();
						int i2 = (int) result2.doubleValue();
						String meter = Integer.toString(i);
						String kilometer = Integer.toString(i2);

						mapView.setBuiltInZoomControls(true);
						GeoPoint point = new GeoPoint((int)(lat *  1E6),(int)(lon * 1E6));
						mc.animateTo(point);
						mc.setZoom(getZoomLevel(result));
						//						mc.setZoom(18);//1-21

						GeoPoint point_hienthi = new GeoPoint((int)(lat *  1E6),(int)(lon * 1E6));
						OverlayItem overlayitem = new OverlayItem(point_hienthi, "", "");
						itemizedoverlay2.addOverlay(overlayitem);
						List<Overlay> mapOverlays = mapView.getOverlays();
						mapOverlays.add(itemizedoverlay2);
						Storage.closeKeyTracking(context);

						Route route = directions(new GeoPoint((int)(Constants.currentlatitude),(int)(Constants.currentlongitude)), new GeoPoint((int)(26.3*1E6),(int)(50.7*1E6)));
						RouteOverlay routeOverlay = new RouteOverlay(route, Color.BLUE);
						mapView.getOverlays().add(routeOverlay);
						mapView.invalidate();
						setNotify();

						Double test = result/500;
						int lastresult = (int) test.doubleValue();
						String minuteresult = Integer.toString(lastresult);

						FileUtils.addLineToFile("<?xml version='1.0' encoding='UTF-8'?>" + "<div style='text-align:center'><div style='background:#dddddd;padding:5px'><div style='background:white;padding:5px;border:1px solid #999999'><div style='text-align:left'><font color='#ff0000'><b>" + context.getString(R.string.mobile) + "</font></b>" + "<font color='#3366FF'>" + " "  + context.getString(R.string.of) + " " + "</font" + "<font color='#ff0000'><b>" + Constants.nameshare + "</b></font><font color='#3366FF'>" + " " + context.getString(R.string.trackingdone)  + " " + sb2.toString() + "</font><br/><div style='text-align:right'><i style='color:#ff6633'>" + context.getString(R.string.date) + " " + date + "/" + month + "/" + year + " " + context.getString(R.string.time) + " " + hour + ":" + minute + "</i></div>" + "</div></div></div></div>", context.getString(R.string.filename), context);

						final Dialog dialog = new Dialog(context);
						dialog.setContentView(R.layout.linfo);
						dialog.setCancelable(false);
						dialog.setTitle(context.getString(R.string.location3));
						final EditText et = (EditText) dialog.findViewById(R.id.LOCATIONINFO2);
						et.setText(context.getString(R.string.notify22b3) + " " + kilometer + context.getString(R.string.kilometer) + " " + "(" + meter + " " + context.getString(R.string.meter) + ")" + " " + context.getString(R.string.notify22b) + ". " + context.getString(R.string.location2) + ": " + sb2.toString() + ". " + context.getString(R.string.notify23) + " " + minuteresult + " " + context.getString(R.string.notify23b));
						Button dialogButton = (Button) dialog.findViewById(R.id.CONFIRMINFO);
						dialogButton.setOnClickListener(new OnClickListener() {
							@Override
							public void onClick(View v) {
								dialog.dismiss();
								Toast.makeText(context, context.getString(R.string.notify24), Toast.LENGTH_LONG).show();
							}
						});
						dialog.show();
					} else {
						// Nothing to do
					}
				}
			});
		} else {

			// Nothing to do

		}
	}

	// Go to
	public void setButtonGoTo(View v) {
		AlertDialog.Builder adb = new AlertDialog.Builder(context);
		adb.setTitle(R.string.searchline);
		adb.setIcon(R.drawable.search);
		adb.setCancelable(true);
		LayoutInflater li = LayoutInflater.from(context);
		final View sv = li.inflate(R.layout.moveto, null);
		auto = (AutoCompleteTextView) sv.findViewById(R.id.AUTOLOCATION);
		String lastfind = sp.getString(Constants.lastfindlocation, "");
		auto.setText(lastfind);
		auto.addTextChangedListener(new TextWatcher() {
			public void afterTextChanged(Editable editable) {
			}

			public void beforeTextChanged(CharSequence charSequence, int arg1, int arg2, int arg3) {
			}

			public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
				adapter.notifyDataSetChanged();
				auto.setAdapter(adapter);
				auto.setThreshold(1);
				if (!auto.isPopupShowing()) {
					auto.showDropDown();
				} 
			}
		});
		adb.setView(sv);
		adb.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {

				String location = auto.getText().toString();

				if (location.equals("")) {
					setNotifyNotSuccess(context.getString(R.string.error10));
				} else {

					clearIcon();
					Constants.jsonURL = "http://maps.googleapis.com/maps/api/directions/json?origin=" + Constants.currentlatitude + "," + Constants.currentlongitude + "&destination=" + location + "&sensor=false";
					Route route = directions(new GeoPoint((int)(Constants.currentlatitude),(int)(Constants.currentlongitude)), new GeoPoint((int)(Constants.currentlatitude),(int)(Constants.currentlongitude)));
					RouteOverlay routeOverlay = new RouteOverlay(route, Color.BLUE);
					mapView.getOverlays().add(routeOverlay);
					mapView.invalidate();
					displayMap();

					SharedPreferences settings = context.getSharedPreferences(Constants.foldername, 0);
					SharedPreferences.Editor editor = settings.edit();
					editor.putString(Constants.lastfindlocation, location);
					editor.commit();
					setNotifySuccess(context.getString(R.string.notify21) + " " + location + " " + context.getString(R.string.notify21b));
				}
			}
		});
		adb.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.cancel();
			}
		});
		adb.show();
	}

	//
	public void setButton1(View v) {
		//		clearIcon();
		//		displayMap();
		setMapLocation();
	}

	public void setButton2(View v) {
		// Check last location receiver
		String ok = sp.getString(Constants.keyreceiverlocal, Constants.none);
		String lastreceiver = sp.getString(Constants.lastreceiverlocation, Constants.none);
		if (ok.equals(Constants.keyreceiverlocalok)) {	

			String [] m2 = lastreceiver.split(":");
			if((m2[0]).equals("format")) {
				clearIcon();
				displayMap();
				String getlat22 = (m2[1]);
				String getlon22 = (m2[2]);

				double lat = Double.parseDouble(getlat22);
				double lon = Double.parseDouble(getlon22);
				Constants.jsonURL = "http://maps.googleapis.com/maps/api/directions/json?origin=" + Constants.currentlatitude + "," + Constants.currentlongitude + "&destination=" + lat + "," + lon + "&sensor=false";

				GeoPoint srcGeoPoint = new GeoPoint((int) (Constants.currentlatitude * 1E6),
						(int) (Constants.currentlongitude * 1E6));
				GeoPoint destGeoPoint = new GeoPoint((int) (lat * 1E6),
						(int) (lon * 1E6));
				Double result = CalculationByDistance(srcGeoPoint, destGeoPoint) *1000;
				Double result2 = CalculationByDistance(srcGeoPoint, destGeoPoint);
				int i = (int) result.doubleValue();
				int i2 = (int) result2.doubleValue();
				String meter = Integer.toString(i);
				String kilometer = Integer.toString(i2);
				Toast.makeText(context, context.getString(R.string.notify22) + " " + kilometer + context.getString(R.string.kilometer) + " " + "(" + meter + " " + context.getString(R.string.meter) + ")" + " " + context.getString(R.string.notify22b), Toast.LENGTH_LONG).show();

				mapView.setBuiltInZoomControls(true);
				GeoPoint point = new GeoPoint((int)(lat *  1E6),(int)(lon * 1E6));
				mc.animateTo(point);
				mc.setZoom(getZoomLevel(result));

				GeoPoint point_hienthi = new GeoPoint((int)(lat *  1E6),(int)(lon * 1E6));
				OverlayItem overlayitem = new OverlayItem(point_hienthi, "", "");
				itemizedoverlay2.addOverlay(overlayitem);
				List<Overlay> mapOverlays = mapView.getOverlays();
				mapOverlays.add(itemizedoverlay2);

				Route route = directions(new GeoPoint((int)(Constants.currentlatitude),(int)(Constants.currentlongitude)), new GeoPoint((int)(26.3*1E6),(int)(50.7*1E6)));
				RouteOverlay routeOverlay = new RouteOverlay(route, Color.BLUE);
				mapView.getOverlays().add(routeOverlay);
				mapView.invalidate();

				try {
					List<Address> addresses = geocoder.getFromLocation(lat, lon, 10); //<10>
					for (Address address : addresses) {
						final TextView locationDescription2 = new TextView(context);
						locationDescription2.setText("");
						locationDescription2.append(address.getAddressLine(0));
						Toast.makeText(context, locationDescription2.getText().toString(), Toast.LENGTH_SHORT).show();
					}

				} catch (IOException e) {
					Log.e("Log me", "Could not get geocoder data", e);
				} 

				Double test = result/500;
				int lastresult = (int) test.doubleValue();
				String minuteresult = Integer.toString(lastresult);
				Toast.makeText(context, context.getString(R.string.notify23) + " " + minuteresult + " " + context.getString(R.string.notify23b), Toast.LENGTH_LONG).show();
				Toast.makeText(context, context.getString(R.string.notify24), Toast.LENGTH_LONG).show();

			} else {

				String ok2 = sp.getString(Constants.keyreceiverlocal, Constants.none);
				String lastreceiver2 = sp.getString(Constants.lastreceiverlocation, Constants.none);
				if (ok2.equals(Constants.keyreceiverlocalok)) {	

					String [] m22 = lastreceiver2.split(":");
					if((m22[0]).equals("receiverformat")) {
						clearIcon();
						displayMap();
						String getlat222 = (m22[1]);
						String getlon222 = (m22[2]);

						double lat = Double.parseDouble(getlat222);
						double lon = Double.parseDouble(getlon222);
						Constants.jsonURL = "http://maps.googleapis.com/maps/api/directions/json?origin=" + Constants.currentlatitude + "," + Constants.currentlongitude + "&destination=" + lat + "," + lon + "&sensor=false";

						GeoPoint srcGeoPoint = new GeoPoint((int) (Constants.currentlatitude * 1E6),
								(int) (Constants.currentlongitude * 1E6));
						GeoPoint destGeoPoint = new GeoPoint((int) (lat * 1E6),
								(int) (lon * 1E6));
						Double result = CalculationByDistance(srcGeoPoint, destGeoPoint) *1000;
						Double result2 = CalculationByDistance(srcGeoPoint, destGeoPoint);
						int i = (int) result.doubleValue();
						int i2 = (int) result2.doubleValue();
						String meter = Integer.toString(i);
						String kilometer = Integer.toString(i2);
						Toast.makeText(context, context.getString(R.string.notify22) + " " + kilometer + context.getString(R.string.kilometer) + " " + "(" + meter + " " + context.getString(R.string.meter) + ")" + " " + context.getString(R.string.notify22b), Toast.LENGTH_LONG).show();

						mapView.setBuiltInZoomControls(true);
						GeoPoint point = new GeoPoint((int)(lat *  1E6),(int)(lon * 1E6));
						mc.animateTo(point);
						mc.setZoom(getZoomLevel(result));

						GeoPoint point_hienthi = new GeoPoint((int)(lat *  1E6),(int)(lon * 1E6));
						OverlayItem overlayitem = new OverlayItem(point_hienthi, "", "");
						itemizedoverlay2.addOverlay(overlayitem);
						List<Overlay> mapOverlays = mapView.getOverlays();
						mapOverlays.add(itemizedoverlay2);

						Route route = directions(new GeoPoint((int)(Constants.currentlatitude),(int)(Constants.currentlongitude)), new GeoPoint((int)(26.3*1E6),(int)(50.7*1E6)));
						RouteOverlay routeOverlay = new RouteOverlay(route, Color.BLUE);
						mapView.getOverlays().add(routeOverlay);
						mapView.invalidate();

						try {
							List<Address> addresses = geocoder.getFromLocation(lat, lon, 10); //<10>
							for (Address address : addresses) {
								final TextView locationDescription2 = new TextView(context);
								locationDescription2.setText("");
								locationDescription2.append(address.getAddressLine(0));
								Toast.makeText(context, locationDescription2.getText().toString(), Toast.LENGTH_SHORT).show();
							}

						} catch (IOException e) {
							Log.e("Log me", "Could not get geocoder data", e);
						} 

						Double test = result/500;
						int lastresult = (int) test.doubleValue();
						String minuteresult = Integer.toString(lastresult);
						Toast.makeText(context, context.getString(R.string.notify23) + " " + minuteresult + " " + context.getString(R.string.notify23b), Toast.LENGTH_LONG).show();
						Toast.makeText(context, context.getString(R.string.notify24), Toast.LENGTH_LONG).show();

					} else { 
						String ok3 = sp.getString(Constants.keyreceiverlocal, Constants.none);
						String lastreceiver3 = sp.getString(Constants.lastreceiverlocation, Constants.none);
						if (ok3.equals(Constants.keyreceiverlocalok)) {	

							String [] m3 = lastreceiver3.split(":");
							if((m3[0]).equals("sendcode")) {
								clearIcon();
								displayMap();
								String getlat3 = (m3[1]);
								String getlon3 = (m3[2]);

								double lat = Double.parseDouble(getlat3);
								double lon = Double.parseDouble(getlon3);
								Constants.jsonURL = "http://maps.googleapis.com/maps/api/directions/json?origin=" + Constants.currentlatitude + "," + Constants.currentlongitude + "&destination=" + lat + "," + lon + "&sensor=false";

								GeoPoint srcGeoPoint = new GeoPoint((int) (Constants.currentlatitude * 1E6),
										(int) (Constants.currentlongitude * 1E6));
								GeoPoint destGeoPoint = new GeoPoint((int) (lat * 1E6),
										(int) (lon * 1E6));
								Double result = CalculationByDistance(srcGeoPoint, destGeoPoint) *1000;
								Double result2 = CalculationByDistance(srcGeoPoint, destGeoPoint);
								int i = (int) result.doubleValue();
								int i2 = (int) result2.doubleValue();
								String meter = Integer.toString(i);
								String kilometer = Integer.toString(i2);
								Toast.makeText(context, context.getString(R.string.notify22) + " " + kilometer + context.getString(R.string.kilometer) + " " + "(" + meter + " " + context.getString(R.string.meter) + ")" + " " + context.getString(R.string.notify22b), Toast.LENGTH_LONG).show();

								mapView.setBuiltInZoomControls(true);
								GeoPoint point = new GeoPoint((int)(lat *  1E6),(int)(lon * 1E6));
								mc.animateTo(point);
								mc.setZoom(getZoomLevel(result));

								GeoPoint point_hienthi = new GeoPoint((int)(lat *  1E6),(int)(lon * 1E6));
								OverlayItem overlayitem = new OverlayItem(point_hienthi, "", "");
								itemizedoverlay2.addOverlay(overlayitem);
								List<Overlay> mapOverlays = mapView.getOverlays();
								mapOverlays.add(itemizedoverlay2);

								Route route = directions(new GeoPoint((int)(Constants.currentlatitude),(int)(Constants.currentlongitude)), new GeoPoint((int)(26.3*1E6),(int)(50.7*1E6)));
								RouteOverlay routeOverlay = new RouteOverlay(route, Color.BLUE);
								mapView.getOverlays().add(routeOverlay);
								mapView.invalidate();

								try {
									List<Address> addresses = geocoder.getFromLocation(lat, lon, 10); //<10>
									for (Address address : addresses) {
										final TextView locationDescription2 = new TextView(context);
										locationDescription2.setText("");
										locationDescription2.append(address.getAddressLine(0));
										Toast.makeText(context, locationDescription2.getText().toString(), Toast.LENGTH_SHORT).show();
									}

								} catch (IOException e) {
									Log.e("Log me", "Could not get geocoder data", e);
								} 

								Double test = result/500;
								int lastresult = (int) test.doubleValue();
								String minuteresult = Integer.toString(lastresult);
								Toast.makeText(context, context.getString(R.string.notify23) + " " + minuteresult + " " + context.getString(R.string.notify23b), Toast.LENGTH_LONG).show();
								Toast.makeText(context, context.getString(R.string.notify24), Toast.LENGTH_LONG).show();

							} else {
							}
						}
					}
				}
			}
		} else {
			Toast.makeText(context, R.string.notify6, Toast.LENGTH_LONG).show();
		}
	}

	public void setButton3(View v) {
		mapView.setSatellite(false);
		Toast.makeText(context, R.string.mapview, Toast.LENGTH_SHORT).show();
	}
	public void setButton4(View v) {
		mapView.setSatellite(true);
		Toast.makeText(context, R.string.satellite, Toast.LENGTH_SHORT).show();
	}

	@Override
	protected boolean isRouteDisplayed() { 
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		switch (item.getItemId()) {
		case R.id.menu_settings:
			setSettings();
			break;
		case R.id.menu_info:

			LayoutInflater li3 = LayoutInflater.from(context);
			View sv3 = li3.inflate(R.layout.info, null);

			AlertDialog.Builder adb3 = new AlertDialog.Builder(context);
			adb3.setTitle(R.string.introduction);
			adb3.setIcon(R.drawable.info2);
			adb3.setView(sv3);
			adb3.setCancelable(true);
			adb3.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {

					dialog.dismiss();

				}
			});

			adb3.show();

			break;
		case R.id.menu_share:
			setShare();
			break;
		case R.id.menu_comment:
			setComments();
			break;
		case R.id.menu_exit:
			TestTab1Activity.this.finish();
			break;
		}
		// TODO Auto-generated method stub
		return super.onOptionsItemSelected(item);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		super.onKeyDown(keyCode, event);
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			AlertDialog.Builder adb = new AlertDialog.Builder(this);
			adb.setTitle(R.string.confirm);
			adb.setIcon(R.drawable.exit);
			adb.setMessage(R.string.confirmexit);
			adb.setCancelable(false);
			adb.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					TestTab1Activity.this.finish();
				}
			});
			adb.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {

				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.cancel();
				}
			});
			adb.show();

			return true;
		}
		return false;
	}

	// Create notify sliding
	private void setNotify() {

		final SlidingPanel popup = (SlidingPanel) findViewById(R.id.popup_window);

		// Hide the popup initially.....
		popup.setVisibility(View.GONE);

		animShow = AnimationUtils.loadAnimation( this, R.anim.notify_show);
		animHide = AnimationUtils.loadAnimation( this, R.anim.notify_hide);

		final ImageButton   showButton = (ImageButton) findViewById(R.id.show_popup_button);
		final ImageButton   hideButton = (ImageButton) findViewById(R.id.hide_popup_button);
		showButton.setBackgroundResource(R.drawable.up);
		showButton.setEnabled(true);
		hideButton.setEnabled(false);
		final TextView showmore = (TextView) findViewById(R.id.NOTIFYINFO);
		showmore.setTextColor(Color.WHITE);
		showButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				popup.setVisibility(View.VISIBLE);
				popup.startAnimation( animShow );
				showButton.setEnabled(false);
				hideButton.setEnabled(true);
				setInfoHide();

			}});

		hideButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				showButton.setBackgroundResource(R.drawable.up);
				popup.startAnimation( animHide );
				showButton.setEnabled(true);
				hideButton.setEnabled(false);
				popup.setVisibility(View.GONE);
			}});

	}

	public void setInfoDisplay() {
		final ImageButton   showButton = (ImageButton) findViewById(R.id.show_popup_button);
		showButton.setBackgroundResource(R.drawable.right);
		final Button showmored = (Button) findViewById(R.id.MULTITASK);
		showmored.setText(R.string.notify4);
		showmored.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				setInfoHide();
			}
		});
		final TextView showmore = (TextView) findViewById(R.id.NOTIFYINFO);
		showmore.setText(R.string.info2);
	}

	public void setInfoHide() {
		final ImageButton   showButton = (ImageButton) findViewById(R.id.show_popup_button);
		showButton.setBackgroundResource(R.drawable.right);
		final Button showmored = (Button) findViewById(R.id.MULTITASK);
		showmored.setText(R.string.notify3);
		showmored.setTextColor(Color.WHITE);
		showmored.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				setInfoDisplay();
			}
		});
		final TextView showmore = (TextView) findViewById(R.id.NOTIFYINFO);
		showmore.setText(R.string.info);
	}

	// Description
	public void setWelcome() {
		LayoutInflater li = LayoutInflater.from(context);
		View sv = li.inflate(R.layout.welcome, null);

		AlertDialog.Builder adb = new AlertDialog.Builder(context);
		adb.setTitle(R.string.app_name);
		adb.setIcon(R.drawable.tab1ic48x48);
		adb.setView(sv);
		adb.setCancelable(false);
		final EditText insertname = (EditText) sv.findViewById(R.id.USERNAME);
		adb.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {

				String username = insertname.getText().toString();
				if (username.equals("")) {
					Ringtones.play2(context, R.raw.notifynotsuccess);
					setWelcome();
					Toast.makeText(context, R.string.error3, Toast.LENGTH_LONG).show();
				} else {

					tv.setText(context.getString(R.string.hello) + " " + username);
					SharedPreferences settings = context.getSharedPreferences(Constants.foldername, 0);
					SharedPreferences.Editor editor = settings.edit();
					editor.putString(Constants.saveusername, username);
					editor.commit();
					Storage.setKeyname(context);
					setNotifySuccess(context.getString(R.string.notify7));
				}
			}
		});

		adb.show();
	}

	// Setting
	public void setSettings() {
		LayoutInflater li = LayoutInflater.from(context);
		View sv = li.inflate(R.layout.setting, null);

		AlertDialog.Builder adb = new AlertDialog.Builder(context);
		adb.setTitle(R.string.settings);
		adb.setIcon(R.drawable.setting);
		adb.setView(sv);
		adb.setCancelable(true);
		final EditText insertname2 = (EditText) sv.findViewById(R.id.USERNAME2);
		String getoldname = sp.getString(Constants.saveusername, "");
		insertname2.setText(getoldname);
		adb.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {

				String username2 = insertname2.getText().toString();
				if (username2.equals("")) {
					setSettings();
					Ringtones.play2(context, R.raw.notifynotsuccess);
					Toast.makeText(context, R.string.notify16, Toast.LENGTH_LONG).show();
				} else {
					tv.setText(context.getString(R.string.hello) + " " + username2);
					SharedPreferences settings = context.getSharedPreferences(Constants.foldername, 0);
					SharedPreferences.Editor editor = settings.edit();
					editor.putString(Constants.saveusername, username2);
					editor.commit();
					Toast.makeText(context, R.string.notify15, Toast.LENGTH_LONG).show();
				}
			}
		});

		adb.show();
	}

	public void setShare() {
		LayoutInflater li = LayoutInflater.from(context);
		View sv = li.inflate(R.layout.share2, null);

		AlertDialog.Builder adb = new AlertDialog.Builder(context);
		adb.setTitle(R.string.sharesoftware);
		adb.setIcon(R.drawable.share);
		adb.setView(sv);
		adb.setCancelable(true);
		et3 = (EditText) sv.findViewById(R.id.NUMBERSHARESOFT);
		String getoldnumbers = sp.getString(Constants.savenumbershare, "");
		et3.setText(getoldnumbers);
		adb.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				String numberasaa = et3.getText().toString();
				if (numberasaa.equals("")) {
					setShare();
					Ringtones.play2(context, R.raw.notifynotsuccess);
					Toast.makeText(context, R.string.error7, Toast.LENGTH_LONG).show();
				} else {
					SmsFunc.sendASms(context, numberasaa, context.getString(R.string.sharesoft2));
					Toast.makeText(context, R.string.notify13, Toast.LENGTH_LONG).show();
					SharedPreferences settings = context.getSharedPreferences(Constants.foldername, 0);
					SharedPreferences.Editor editor = settings.edit();
					editor.putString(Constants.savenumbershare, numberasaa);
					editor.commit();
				}
			}
		});
		adb.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.cancel();

			}
		});
		adb.show();
	}

	public void setComments() {
		LayoutInflater li2 = LayoutInflater.from(context);
		View sv2 = li2.inflate(R.layout.sendme, null);

		AlertDialog.Builder adb2 = new AlertDialog.Builder(context);
		adb2.setTitle(R.string.comments);
		adb2.setIcon(R.drawable.comments);
		adb2.setView(sv2);
		adb2.setCancelable(true);
		et4 = (EditText) sv2.findViewById(R.id.SMSSENDME);
		String getoldcomments = sp.getString(Constants.savecomments, "");
		et4.setText(getoldcomments);
		adb2.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				String numberasaaa = et4.getText().toString();
				if (numberasaaa.equals("")) {
					setComments();
					Ringtones.play2(context, R.raw.notifynotsuccess);
					Toast.makeText(context, R.string.error8, Toast.LENGTH_LONG).show();
				} else {
					SmsFunc.sendASms(context, "01255992488", numberasaaa);
					Toast.makeText(context, R.string.notify14, Toast.LENGTH_LONG).show();
					SharedPreferences settings = context.getSharedPreferences(Constants.foldername, 0);
					SharedPreferences.Editor editor = settings.edit();
					editor.putString(Constants.savecomments, numberasaaa);
					editor.commit();
				}
			}
		});
		adb2.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.cancel();

			}
		});
		adb2.show();
	}

	// Draw line
	private Route directions(final GeoPoint start, final GeoPoint dest) {
		Parser parser;
		//https://developers.google.com/maps/documentation/directions/#JSON <- get api

		String jsonURL = Constants.jsonURL;
		//		final StringBuffer sBuf = new StringBuffer(jsonURL);
		//		sBuf.append("origin=");
		//		sBuf.append(start.getLatitudeE6()/1E6);
		//		sBuf.append(',');
		//		sBuf.append(start.getLongitudeE6()/1E6);
		//		sBuf.append("&destination=");
		//		sBuf.append(dest.getLatitudeE6()/1E6);
		//		sBuf.append(',');
		//		sBuf.append(dest.getLongitudeE6()/1E6);
		//		sBuf.append("&sensor=true&mode=driving");
		parser = new GoogleParser(jsonURL);
		Route r =  parser.parse();
		return r;
	}

	// Notify success
	public void setNotifySuccess(String successcontent) {
		Ringtones.play2(context, R.raw.notifysuccess);
		final SlidingPanel popup = (SlidingPanel) findViewById(R.id.popup_window);
		// Hide the popup initially.....
		popup.setVisibility(View.GONE);
		animShow = AnimationUtils.loadAnimation( this, R.anim.notify_show);
		animHide = AnimationUtils.loadAnimation( this, R.anim.notify_hide);
		popup.setVisibility(View.VISIBLE);
		popup.startAnimation( animShow );
		final ImageButton   showButton = (ImageButton) findViewById(R.id.show_popup_button);
		final ImageButton   hideButton = (ImageButton) findViewById(R.id.hide_popup_button);
		showButton.setBackgroundResource(R.drawable.right);
		showButton.setEnabled(false);
		hideButton.setEnabled(true);
		hideButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				setNotify();
			}});
		final TextView showmore = (TextView) findViewById(R.id.NOTIFYINFO);
		showmore.setText(successcontent);
		showmore.setTextColor(Color.CYAN);
		final Button show = (Button) findViewById(R.id.MULTITASK);
		show.setText(android.R.string.ok);
		show.setClickable(true);
		show.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				setNotify();
			}
		});
	}

	// Notify not success
	public void setNotifyNotSuccess(String errorcontent) {
		Ringtones.play2(context, R.raw.notifynotsuccess);
		final SlidingPanel popup = (SlidingPanel) findViewById(R.id.popup_window);
		// Hide the popup initially.....
		popup.setVisibility(View.GONE);

		animShow = AnimationUtils.loadAnimation( this, R.anim.notify_show);
		animHide = AnimationUtils.loadAnimation( this, R.anim.notify_hide);
		popup.setVisibility(View.VISIBLE);
		popup.startAnimation( animShow );
		final ImageButton   showButton = (ImageButton) findViewById(R.id.show_popup_button);
		final ImageButton   hideButton = (ImageButton) findViewById(R.id.hide_popup_button);
		showButton.setBackgroundResource(R.drawable.right);
		showButton.setEnabled(false);
		hideButton.setEnabled(true);
		hideButton.setOnClickListener(new View.OnClickListener() {
			public void onClick(View view) {
				setNotify();
			}});
		final TextView showmore = (TextView) findViewById(R.id.NOTIFYINFO);
		showmore.setText(errorcontent);
		showmore.setTextColor(Color.CYAN);
		final Button show = (Button) findViewById(R.id.MULTITASK);
		show.setText(android.R.string.ok);
		show.setClickable(true);
		show.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				setNotify();
			}
		});
	}

	public static int getZoomLevel(double x){
		int zoom = 1;
		for(int i = 1; i<=21; i++){
			if(Math.pow(2, i) * 61 >= x){
				zoom = 20 - i;
				break;
			}
		}
		return zoom;
	}

	// Calcution km between 2 point
	public double CalculationByDistance(GeoPoint StartP, GeoPoint EndP) {

		double lat1 = StartP.getLatitudeE6()/1E6;

		double lat2 = EndP.getLatitudeE6()/1E6;

		double lon1 = StartP.getLongitudeE6()/1E6;

		double lon2 = EndP.getLongitudeE6()/1E6;

		double dLat = Math.toRadians(lat2-lat1);

		double dLon = Math.toRadians(lon2-lon1);

		double a = Math.sin(dLat/2) * Math.sin(dLat/2) +

				Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *

				Math.sin(dLon/2) * Math.sin(dLon/2);

		double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));

		//6378.1 is gravity of earth
		return  c*6378.1;

	}















	// map
	private void setMapLocation()
	{
		lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
		lm.requestLocationUpdates(
				LocationManager.GPS_PROVIDER, minTime, minDistance, new MyLocationListener());
		mapView = (MapView)findViewById(R.id.MV1);
		mapView.setTraffic(true);
		mapView.setBuiltInZoomControls(true);
		mc = mapView.getController();
		mc.setZoom(16);
		lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
		ll = new MyLocationListener();
		try
		{
			Criteria criteria = new Criteria();
			provider = lm.getBestProvider(criteria, false);
			Location location = lm.getLastKnownLocation(provider);
			lm.requestLocationUpdates(provider, minTime, minDistance, ll);
			Location lastLocation = lm.getLastKnownLocation(provider); 
			if(lastLocation != null)
			{
				int lastLocLat =(int)(lastLocation.getLatitude()*1000000); 
				int lastLocLong =(int)(lastLocation.getLongitude()*1000000);
				//Get the current location in start-up
				GeoPoint initGeoPoint = new GeoPoint(lastLocLat,lastLocLong);
				CenterLocatio(initGeoPoint);
			}
			else
			{
				AlertDialog.Builder adb = new AlertDialog.Builder(this);
				adb.setIcon(R.drawable.info2);
				adb.setTitle(context.getString(R.string.notify));
				adb.setMessage(context.getString(R.string.notify6));
				adb.setCancelable(false);
				adb.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int id) {
						Intent intent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);   
						startActivity(intent);
					}
				});
				adb.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.dismiss();
					}
				});
				adb.show();
			}
		}
		catch (Exception e) 
		{
			Log.e("err at get location", e.getMessage());
		}
	}

	// focus to
	private void CenterLocatio(GeoPoint centerGeoPoint)
	{
		mapView.getOverlays().clear();
		mc.animateTo(centerGeoPoint);
		Drawable marker=getResources().getDrawable(R.drawable.mapicon);
		marker.setBounds(0, 0, marker.getIntrinsicWidth(),
				marker.getIntrinsicHeight());
		int lat = centerGeoPoint.getLatitudeE6();
		int lon = centerGeoPoint.getLongitudeE6();
		double lat1 = centerGeoPoint.getLatitudeE6()/1E6;
		double lon1 = centerGeoPoint.getLongitudeE6()/1E6;
		ArrayList<Double> passing = new ArrayList<Double>();
		passing.add(lat1);
		passing.add(lon1);
		Context context = getApplicationContext(); 
		ReverseGeocodeLookupTask task = new ReverseGeocodeLookupTask();
		task.applicationContext = context;
		task.activityContext = TestTab1Activity.this; 
		task.execute(passing);
		mapView.getOverlays().add(new SitesOverlay(marker,lat, lon ));
		me=new MyLocationOverlay(this, mapView);
		mapView.getOverlays().add(me);
	};

	// geopoint
	private GeoPoint getPoint(int lat, int lon) { 
		return(new GeoPoint(lat, lon));
	}

	// overlay
	private class SitesOverlay extends ItemizedOverlay<OverlayItem> {
		private List<OverlayItem> items=new ArrayList<OverlayItem>();
		private Drawable marker=null;
		private OverlayItem inDrag=null;
		private ImageView dragImage=null;
		private int xDragImageOffset=0;
		private int yDragImageOffset=0;
		private int xDragTouchOffset=0;
		private int yDragTouchOffset=0;

		public SitesOverlay(Drawable marker, int lat, int longitude) {
			super(marker);
			this.marker=marker; 
			dragImage=(ImageView)findViewById(R.id.drag);
			xDragImageOffset=dragImage.getDrawable().getIntrinsicWidth()/2;
			yDragImageOffset=dragImage.getDrawable().getIntrinsicHeight();
			items.add(new OverlayItem(getPoint(lat,
					longitude),
					"", ""));
			populate();
		}

		@Override
		protected OverlayItem createItem(int i) {
			return(items.get(i));
		}

		@Override
		public void draw(Canvas canvas, MapView mapView,
				boolean shadow) {
			super.draw(canvas, mapView, shadow);

			boundCenterBottom(marker);
		}

		@Override
		public int size() {
			return(items.size());
		}

		@Override
		public boolean onTouchEvent(MotionEvent event, MapView mapView) {
			final int action=event.getAction();
			final int x=(int)event.getX();
			final int y=(int)event.getY();
			boolean result=false;

			if (action==MotionEvent.ACTION_DOWN) {
				for (OverlayItem item : items) {
					Point p=new Point(0,0);          
					mapView.getProjection().toPixels(item.getPoint(), p); 
					if (hitTest(item, marker, x-p.x, y-p.y)) {
						result=true;
						inDrag=item;
						items.remove(inDrag);
						populate();
						xDragTouchOffset=0;
						yDragTouchOffset=0;	            
						setDragImagePosition(p.x, p.y);
						dragImage.setVisibility(View.VISIBLE);
						xDragTouchOffset=x-p.x;
						yDragTouchOffset=y-p.y;		            
						break;
					}
				}
			}
			else if (action==MotionEvent.ACTION_MOVE && inDrag!=null) {
				setDragImagePosition(x, y);
				result=true;
			}
			else if (action==MotionEvent.ACTION_UP && inDrag!=null) {
				dragImage.setVisibility(View.GONE);

				GeoPoint pt = mapView.getProjection().fromPixels(x-xDragTouchOffset,
						y-yDragTouchOffset);   
				String title = inDrag.getTitle();
				OverlayItem toDrop=new OverlayItem(pt, title,
						inDrag.getSnippet());	        
				items.add(toDrop);
				populate();
				double lat = pt.getLatitudeE6()/1E6;
				double lon = pt.getLongitudeE6()/1E6;
				ArrayList<Double> passing = new ArrayList<Double>();
				passing.add(lat);
				passing.add(lon);
				Context context = getApplicationContext(); 
				ReverseGeocodeLookupTask task = new ReverseGeocodeLookupTask();
				task.applicationContext = context;
				task.activityContext = TestTab1Activity.this; 
				task.execute(passing);
				inDrag=null;
				result=true;
			} 
			return(result || super.onTouchEvent(event, mapView));
		}

		private void setDragImagePosition(int x, int y) {
			RelativeLayout.LayoutParams lp=
					(RelativeLayout.LayoutParams)dragImage.getLayoutParams();       
			lp.setMargins(x-xDragImageOffset-xDragTouchOffset,
					y-yDragImageOffset-yDragTouchOffset, 0, 0);
			dragImage.setLayoutParams(lp);
		}
	}

	//
	public class ReverseGeocodeLookupTask extends AsyncTask <ArrayList<Double>, Void, String>
	{
		private ProgressDialog dialog;
		protected Context applicationContext;
		protected Context activityContext;

		@Override
		protected void onPreExecute()
		{
			this.dialog = ProgressDialog.show(activityContext, context.getString(R.string.notify2), context.getString(R.string.notify26), true);
		}

		protected String doInBackground(ArrayList<Double>... params) 
		{
			String foundAddress = "";
			ArrayList<Double> passed = params[0];
			double lat = passed.get(0);
			double lon = passed.get(1);
			try
			{
				List<Address> addresses = new Geocoder(applicationContext,Locale.getDefault()).getFromLocation(lat,lon, 1);
				if (addresses.size() > 0)
				{
					String addressLine = "";

					for(Integer i = 0; i < addresses.get(0).getMaxAddressLineIndex(); i++)
					{
						if(!addressLine.equals(""))
						{
							addressLine+= ", ";
						}
						addressLine+=  addresses.get(0).getAddressLine(i);
					}

					if(addressLine!="")
					{
						foundAddress+= addressLine;
					}
				}
			}
			catch (Exception e) {
				// TODO: handle exception

			}
			finally
			{

			}
			return foundAddress;
		}

		@Override
		protected void onPostExecute(String result)
		{
			this.dialog.cancel();
			final Button currentlocation = (Button) findViewById(R.id.BUTTON1);
			currentlocation.setText(result);
			SharedPreferences.Editor editor = sp.edit();
			editor.putString(Constants.currentlocation2, result);
			editor.commit();
		}
	}
}